import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/system/data/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import loginApi from '@/api/index'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      // 顶部导航菜单默认添加统计报表栏指向首页
      const index = [{
        path: 'index',
        meta: { title: '统计报表', icon: 'dashboard' }
      }]
      state.topbarRouters = routes.concat(index)
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes ({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        //  loginApi.getRouters().then(res => {
        const res = {
          msg: '操作成功',
          code: 200,
          data: [
            // 活动收集
            {
              name: 'activeCollection',
              path: '/activeCollection',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '活动收集', icon: 'system', noCache: false, link: null },
              children: [{
                name: 'activeList',
                path: 'activeList',
                hidden: false,
                component: 'activeCollection/activeList.vue',
                meta: { title: '活动收集列表', icon: 'user', noCache: false, link: null }
              }]
            },
            // 月子中心管理
            {
              name: 'yueziCenter',
              path: '/yueziCenter',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '月子中心管理', icon: 'system', noCache: false, link: null },
              children: [{
                name: 'YueziList',
                path: 'yueziList',
                hidden: false,
                component: 'yueziCenter/YueziList.vue',
                meta: { title: '月子中心列表', icon: 'user', noCache: false, link: null }
              },
              {
                name: 'YueziAudit',
                path: 'yueziAudit',
                hidden: false,
                component: 'yueziCenter/YueziAudit.vue',
                meta: { title: '月子中心审核', icon: 'peoples', noCache: false, link: null }
              }]
            },
            // 客户管理
            {
              name: 'Monitor',
              path: '/customer',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '客户管理', icon: 'monitor', noCache: false, link: null },
              children: [{
                name: 'Online',
                path: 'clientList',
                hidden: false,
                component: 'customer/clientList.vue',
                meta: { title: '客户列表', icon: 'online', noCache: false, link: null }
              },
              {
                name: 'Job',
                path: 'job',
                hidden: false,
                component: 'customer/clientAudit.vue',
                meta: { title: '客户审核', icon: 'job', noCache: false, link: null }
              }]
            },
            // 订单管理
            {
              name: 'Tool',
              path: '/orderFrom',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '订单管理', icon: 'tool', noCache: false, link: null },
              children: [{
                name: 'Build',
                path: 'orderFromList',
                hidden: false,
                component: 'orderFrom/orderFromList.vue',
                meta: { title: '订单列表', icon: 'build', noCache: false, link: null }
              },
              {
                name: 'Gen',
                path: 'orderFromAudit',
                hidden: false,
                component: 'orderFrom/orderFromAudit.vue',
                meta: { title: '订单审核', icon: 'code', noCache: false, link: null }
              }]
            },
            // 产品柜业务
            {
              name: 'productTank',
              path: '/productTank',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '产品柜业务', icon: 'tool', noCache: false, link: null },
              children: [{
                name: 'productTankManagement',
                path: 'productTankManagement',
                hidden: false,
                component: 'productTank/ProductTankManagement.vue',
                meta: { title: '产品柜管理', icon: 'build', noCache: false, link: null }
              }]
            },
            // 礼包派发业务
            {
              name: 'gift',
              path: '/gift',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '礼包派发业务', icon: 'tool', noCache: false, link: null },
              children: [{
                name: 'Build',
                path: 'giftApple',
                hidden: false,
                component: 'gift/giftApple.vue',
                meta: { title: '礼包申请管理', icon: 'build', noCache: false, link: null }
              },
              {
                name: 'giftGet',
                path: 'giftGet',
                hidden: false,
                component: 'gift/giftGet.vue',
                meta: { title: '礼包领取管理', icon: 'code', noCache: false, link: null }
              },
              {
                name: 'giftGetVoucher',
                path: 'giftGetVoucher',
                hidden: false,
                component: 'gift/giftGetVoucher.vue',
                meta: { title: '礼包领取凭证管理', icon: 'code', noCache: false, link: null }
              }
              ]
            },

            // 财务管理
            {
              name: 'finance',
              path: '/finance',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '财务管理', icon: 'tool', noCache: false, link: null },
              children: [{
                name: 'Contract',
                path: 'contract',
                hidden: false,
                component: 'finance/Contract.vue',
                meta: { title: '产品柜合同管理', icon: 'build', noCache: false, link: null }
              },
              {
                name: 'Invoice',
                path: 'invoice',
                hidden: false,
                component: 'finance/Invoice.vue',
                meta: { title: '发票管理', icon: 'code', noCache: false, link: null }
              },
              {
                name: 'Borrow',
                path: 'borrow',
                hidden: false,
                component: 'finance/Borrow.vue',
                meta: { title: '借款凭证管理', icon: 'code', noCache: false, link: null }
              }
              ]
            },
            // 消息管理
            {
              name: 'newsManage',
              path: '/newsManage',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '消息管理', icon: 'tool', noCache: false, link: null },
              children: [{
                name: 'News',
                path: 'news',
                hidden: false,
                component: 'newsManage/News.vue',
                meta: { title: '消息列表', icon: 'build', noCache: false, link: null }
              },
              {
                name: 'NewsTemplate',
                path: 'newsTemplate',
                hidden: false,
                component: 'newsManage/NewsTemplate.vue',
                meta: { title: '消息模板', icon: 'code', noCache: false, link: null }
              }
              ]
            },
            {
              name: 'TrainingCourse',
              path: '/trainingCourse',
              hidden: false,
              redirect: 'noRedirect',
              component: 'Layout',
              alwaysShow: true,
              meta: { title: '陪训课程', icon: 'tool', noCache: false, link: null },
              children: [{
                name: 'CourseList',
                path: 'courseList',
                hidden: false,
                component: 'trainingCourse/CourseList.vue',
                meta: { title: '课程列表管理', icon: 'build', noCache: false, link: null }
              },
              {
                name: 'CourseOpen',
                path: 'courseOpen',
                hidden: false,
                component: 'trainingCourse/CourseOpen.vue',
                meta: { title: '课程陪训开放管理', icon: 'code', noCache: false, link: null }
              },
              {
                name: 'Video',
                path: 'video',
                hidden: false,
                component: 'trainingCourse/Video.vue',
                meta: { title: '视频分类设置', icon: 'code', noCache: false, link: null }
              }
              ]
            }
          ]
        }
        console.log(res.data, 'res.data')
        const sdata = JSON.parse(JSON.stringify(res.data))
        const rdata = JSON.parse(JSON.stringify(res.data))
        const sidebarRoutes = filterAsyncRouter(sdata)
        const rewriteRoutes = filterAsyncRouter(rdata, false, true)
        const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
        rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(asyncRoutes)
        commit('SET_ROUTES', rewriteRoutes)
        commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
        commit('SET_DEFAULT_ROUTES', sidebarRoutes)
        commit('SET_TOPBAR_ROUTES', sidebarRoutes)
        resolve(rewriteRoutes)
        // })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter (asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route.children
      delete route.redirect
    }
    return true
  })
}

function filterChildren (childrenMap, lastRouter = false) {
  let children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes (routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    // return () => import(`@/views/${view}`)
    return (resolve) => require([`@/views/${view}`], resolve)
  }
}

export default permission
